import React, { useState, useEffect } from 'react';
import { Card, Button, Input, message, Spin, Typography, Space, Divider, Tag } from 'antd';
import { DownloadOutlined, LockOutlined, FileOutlined, CalendarOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';

const { Title, Text, Paragraph } = Typography;

interface ShareInfo {
  success: boolean;
  requiresPassword?: boolean;
  fileName?: string;
  fileSize?: number;
  message?: string;
}

const SharePage: React.FC = () => {
  const { shareToken } = useParams<{ shareToken: string }>();
  const navigate = useNavigate();
  const [shareInfo, setShareInfo] = useState<ShareInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [password, setPassword] = useState('');
  const [verifying, setVerifying] = useState(false);

  useEffect(() => {
    if (shareToken) {
      fetchShareInfo();
    }
  }, [shareToken]);

  const fetchShareInfo = async () => {
    try {
      setLoading(true);
      const response = await fetch(`http://localhost:3002/api/cloud-storage/share/${shareToken}/info`);
      const data = await response.json();
      setShareInfo(data);
    } catch (error) {
      console.error('获取分享信息失败:', error);
      setShareInfo({
        success: false,
        message: '获取分享信息失败'
      });
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async () => {
    if (!password.trim()) {
      message.error('请输入密码');
      return;
    }

    try {
      setVerifying(true);
      const response = await fetch(`http://localhost:3002/api/cloud-storage/share/${shareToken}/verify`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ password }),
      });

      if (response.ok) {
        // 密码验证成功，直接下载文件
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = shareInfo?.fileName || 'download';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('文件下载成功');
      } else {
        const errorData = await response.json();
        message.error(errorData.message || '密码错误');
      }
    } catch (error) {
      console.error('密码验证失败:', error);
      message.error('密码验证失败');
    } finally {
      setVerifying(false);
    }
  };

  const handleDirectDownload = async () => {
    try {
      const response = await fetch(`http://localhost:3002/api/cloud-storage/share/${shareToken}/download`);
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = shareInfo?.fileName || 'download';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('文件下载成功');
      } else {
        const errorData = await response.json();
        message.error(errorData.message || '下载失败');
      }
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败');
    }
  };

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '100vh',
        background: '#f5f5f5'
      }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!shareInfo?.success) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '100vh',
        background: '#f5f5f5'
      }}>
        <Card style={{ width: 400, textAlign: 'center' }}>
          <Title level={3} type="danger">分享链接无效</Title>
          <Paragraph>{shareInfo?.message || '分享链接不存在或已过期'}</Paragraph>
          <Button type="primary" onClick={() => navigate('/')}>
            返回首页
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ 
      display: 'flex', 
      justifyContent: 'center', 
      alignItems: 'center', 
      minHeight: '100vh',
      background: '#f5f5f5',
      padding: '20px'
    }}>
      <Card style={{ width: 500, maxWidth: '90vw' }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <FileOutlined style={{ fontSize: 48, color: '#1890ff', marginBottom: 16 }} />
          <Title level={3}>文件分享</Title>
        </div>

        <div style={{ marginBottom: 24 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div>
              <Text strong>文件名：</Text>
              <Text>{shareInfo.fileName}</Text>
            </div>
            <div>
              <Text strong>文件大小：</Text>
              <Text>{formatFileSize(shareInfo.fileSize || 0)}</Text>
            </div>
            {shareInfo.requiresPassword && (
              <div>
                <Tag icon={<LockOutlined />} color="orange">需要密码</Tag>
              </div>
            )}
          </Space>
        </div>

        <Divider />

        {shareInfo.requiresPassword ? (
          <div>
            <Title level={5}>请输入访问密码</Title>
            <Space.Compact style={{ width: '100%', marginBottom: 16 }}>
              <Input.Password
                placeholder="请输入密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                onPressEnter={handlePasswordSubmit}
                style={{ flex: 1 }}
              />
              <Button 
                type="primary" 
                onClick={handlePasswordSubmit}
                loading={verifying}
                icon={<DownloadOutlined />}
              >
                下载
              </Button>
            </Space.Compact>
          </div>
        ) : (
          <div style={{ textAlign: 'center' }}>
            <Button 
              type="primary" 
              size="large"
              icon={<DownloadOutlined />}
              onClick={handleDirectDownload}
              style={{ width: '100%' }}
            >
              下载文件
            </Button>
          </div>
        )}

        <Divider />

        <div style={{ textAlign: 'center', color: '#999' }}>
          <Text type="secondary">
            <CalendarOutlined /> 分享链接由云存储系统提供
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default SharePage;
